<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="500px"
    append-to-body
    :close-on-click-modal="false"
    @close="closeModal"
  >
    <el-form ref="form" :model="form" :show-message="false" label-width="120px">
      <el-form-item label="药材类别名称" prop="categoryName" required>
        <el-input
          v-model="form.categoryName"
          placeholder="请输入药材类别名称"
          :maxLength="20"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item label="药材类别说明" prop="categoryDesc">
        <el-input
          v-model="form.categoryDesc"
          placeholder="请输入药材类别说明"
          type="textarea"
          :rows="3"
          clearable
          :maxLength="2000"
        ></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="open = false">取 消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { addDrugClass, updateDrugClass } from "@/api/saas/tcm.js";
import { deepClone } from '@/utils';

export default {
  data() {
    return {
      title: "新建药材类别",
      open: false,
      form: {},
    };
  },
  methods: {
    openModal(row) {
      this.title = row && row.categoryId ? '编辑药材类别' : '新建药材类别';
      this.open = true;
      this.form = row && row.categoryId ? deepClone(row) : { categoryId: undefined, categoryName: undefined, categoryDesc: undefined }
    },
    closeModal() {
      this.$refs["form"].resetFields();
      Object.assign(this.$data, this.$options.data()); // 存在自定义校验规则不能重置data
    },
    submitForm() {
      const that = this;
      that.$refs["form"].validate(async (valid) => {
        if (valid) {
          if (that.form.categoryId) {
            await updateDrugClass(that.form);
          } else {
            await addDrugClass(that.form);
          }
          that.$message.success(that.form.categoryId ? "修改成功" : "新增成功");
          that.$emit("refresh");
          that.closeModal();
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped></style>
